package com.amap.rideroute;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.RouteSearch.RideRouteQuery;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.rideroute.bean.AddressPointBean;
import com.amap.rideroute.util.AMapUtil;
import com.amap.rideroute.util.SortPathUtil;
import com.amap.rideroute.util.ToastUtil;
import com.amap.rideroute.overlay.RideRouteOverlay;
import com.blankj.utilcode.util.ScreenUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yinglan.scrolllayout.ScrollLayout;

import java.util.ArrayList;
import java.util.List;


public class RideRouteActivity extends Activity implements OnMapClickListener,
        OnMarkerClickListener, OnInfoWindowClickListener, InfoWindowAdapter, OnRouteSearchListener, AMap.OnMapLoadedListener {
    private AMap aMap;
    private MapView mapView;
    private Context mContext;
    private RouteSearch mRouteSearch;
    private RideRouteResult mRideRouteResult;
    private ScrollLayout slFloatcontainer;
    private RecyclerView rvAddresslist;
    private final int ROUTE_TYPE_RIDE = 4;
    private List<AddressPointBean> latLonPoints;
    private BaseQuickAdapter<AddressPointBean, BaseViewHolder> baseQuickAdapter;
    private double mCurrentLatitude;
    private double mCurrentLongitude;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.route_activity);
        mContext = this.getApplicationContext();
        mapView = (MapView) findViewById(R.id.route_map);
        slFloatcontainer = (ScrollLayout)findViewById(R.id.sl_floatcontainer);
        rvAddresslist = (RecyclerView)findViewById(R.id.rv_addresslist);
        mapView.onCreate(bundle);// 此方法必须重写
        init();
    }
    private void initScrollLayout() {
        slFloatcontainer.setMinOffset(0);
        int dimensionPixelOffset = getResources().getDimensionPixelOffset(R.dimen.dp_170);
        slFloatcontainer.setMaxOffset(dimensionPixelOffset);
        slFloatcontainer.setExitOffset(dimensionPixelOffset);
        slFloatcontainer.setIsSupportExit(true);
        slFloatcontainer.setAllowHorizontalScroll(true);
        slFloatcontainer.setToExit();
        slFloatcontainer.setOnScrollChangedListener(mOnScrollChangedListener);
    }
    private ScrollLayout.OnScrollChangedListener mOnScrollChangedListener = new ScrollLayout.OnScrollChangedListener() {
        @Override
        public void onScrollProgressChanged(float currentProgress) {

        }

        @Override
        public void onScrollFinished(ScrollLayout.Status currentStatus) {
            switch (currentStatus) {
                case OPENED:
                    break;
                case EXIT:
                    break;
                case CLOSED:
                    break;
            }
        }

        @Override
        public void onChildScroll(int top) {
        }
    };
    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        preAddress();
        registerListener();
        initLocation();
        initScrollLayout();
    }

    /**
     * 预处理地址列表（相当于真实环境的获取接口的地址列表）
     */
    private void preAddress() {
        //模拟的多个位置
        latLonPoints = new ArrayList<>();
        latLonPoints.add(new AddressPointBean(new LatLonPoint(36.682871, 117.123232),"济南市历下区工业南路59号中铁财智中心1号楼103室"));
        latLonPoints.add(new AddressPointBean(new LatLonPoint(36.689582, 117.129498),"济南市历下区盛世花城(康虹路南)"));
        latLonPoints.add(new AddressPointBean(new LatLonPoint(36.684248, 117.139325),"济南市历下区天辰大街978号"));
    }

    //开始定位
    private void initLocation() {//1 定位  2 定位+开始服务
        aMap.clear();
        AMapLocationClient mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //保存当前的位置
                        mCurrentLatitude = aMapLocation.getLatitude();
                        mCurrentLongitude = aMapLocation.getLongitude();
                        //根据地址距当前的距离对地址进行排序
                        latLonPoints = SortPathUtil.sortStraightPath(new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude()), latLonPoints);
                        initAddressList();
                        Log.e("排序", latLonPoints.size() + "");
                        //根据所有的点计算出边界点的区域，然后展示最小包裹所有点的区域
                        try {
                            ArrayList<LatLonPoint> boundsPoints = new ArrayList<>();
                            for (int i = 0; i < latLonPoints.size(); i++) {
                                AddressPointBean latLonPoint = latLonPoints.get(i);
                                if(i == 0){
                                    boundsPoints.add(latLonPoint.getLatLonPoints()[0]);
                                }
                                boundsPoints.add(latLonPoint.getLatLonPoints()[1]);
                            }
                            LatLngBounds latLngBounds = AMapUtil.getLatLngBounds(boundsPoints);
                            aMap.animateCamera(CameraUpdateFactory
                                    .newLatLngBounds(latLngBounds, 50));
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                        drawLine();
                    }
                }
            }
        });
        mLocationClient.startLocation();
    }
    private void drawLine(){
        //先添加当前位置的标志
        AddressPointBean addressPointUser = latLonPoints.get(0);
        aMap.addMarker((new MarkerOptions())
                .position(new LatLng(addressPointUser.getLatLonPoints()[0].getLatitude(), addressPointUser.getLatLonPoints()[0].getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_usermark)));
        for (int i = 0; i < latLonPoints.size(); i++) {
            final AddressPointBean addressPointBean = latLonPoints.get(i);
            //添加订单顺序标记
            TextView textView = new TextView(this);
            textView.setBackgroundResource(R.drawable.shape_numbg);
            textView.setTextColor(Color.WHITE);
            textView.setGravity(Gravity.CENTER);
            textView.setWidth(100);
            textView.setHeight(100);
            textView.setTextSize(20);
            textView.setText((i + 1) + "");
            aMap.addMarker((new MarkerOptions())
                    .position(new LatLng(addressPointBean.getLatLonPoints()[1].getLatitude(), addressPointBean.getLatLonPoints()[1].getLongitude())).icon(BitmapDescriptorFactory.fromView(textView)));
            //路径规划
            searchRouteResult(addressPointBean.getLatLonPoints(), ROUTE_TYPE_RIDE, RouteSearch.RIDING_DEFAULT);
        }
    }
    private void initAddressList() {
        if(baseQuickAdapter == null){
            baseQuickAdapter = new BaseQuickAdapter<AddressPointBean, BaseViewHolder>(R.layout.item_address, latLonPoints) {
                @Override
                protected void convert(BaseViewHolder helper, AddressPointBean item) {
                    TextView tvNum = helper.getView(R.id.tv_num);
                    TextView tvAddress = helper.getView(R.id.tv_address);
                    TextView tvDistance = helper.getView(R.id.tv_distance);
                    tvNum.setText(helper.getLayoutPosition() + "");
                    tvAddress.setText(item.getAddressName());
                    LatLng currentLatLng = new LatLng(mCurrentLatitude, mCurrentLongitude);
                    LatLng addresstLatLng = new LatLng(item.getCurrentPoint().getLatitude(), item.getCurrentPoint().getLongitude());
                    float distance = AMapUtils.calculateLineDistance(currentLatLng,addresstLatLng);
                    if(distance >= 1000){
                        distance = distance / 1000;
                        tvDistance.setText("距离："+distance + "km");
                    }else {
                        tvDistance.setText("距离："+distance + "m");
                    }
                }
            };
            baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    //将点击的地址置顶
                    latLonPoints.get(position).setShowTop(true);
                    //重新绘制路径及点的位置
                    initLocation();
                    //点击后自动显示地图
                    slFloatcontainer.scrollToOpen();
                }
            });
            View headerView = View.inflate(this, R.layout.view_header, null);
            baseQuickAdapter.addHeaderView(headerView);
            rvAddresslist.setLayoutManager(new LinearLayoutManager(this));
            rvAddresslist.setAdapter(baseQuickAdapter);
        }else {
            baseQuickAdapter.setNewData(latLonPoints);
            baseQuickAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 注册监听
     */
    private void registerListener() {
        aMap.setOnMapLoadedListener(RideRouteActivity.this);
        aMap.setOnMapClickListener(RideRouteActivity.this);
        aMap.setOnMarkerClickListener(RideRouteActivity.this);
        aMap.setOnInfoWindowClickListener(RideRouteActivity.this);
        aMap.setInfoWindowAdapter(RideRouteActivity.this);
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
    }

    @Override
    public View getInfoContents(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public View getInfoWindow(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onMarkerClick(Marker arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onMapClick(LatLng arg0) {
        // TODO Auto-generated method stub

    }


    /**
     * 开始搜索路径规划方案
     */
    public synchronized void searchRouteResult(LatLonPoint[] points, int routeType, int mode) {
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                points[0], points[1]);
        if (routeType == ROUTE_TYPE_RIDE) {// 骑行路径规划
            RideRouteQuery query = new RideRouteQuery(fromAndTo, mode);
            mRouteSearch.calculateRideRouteAsyn(query);// 异步路径规划骑行模式查询
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult result, int errorCode) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {

    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onRideRouteSearched(final RideRouteResult result, final int errorCode) {
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mRideRouteResult = result;
                    final RidePath ridePath = mRideRouteResult.getPaths()
                            .get(0);
                    RideRouteOverlay rideRouteOverlay = new RideRouteOverlay(
                            RideRouteActivity.this, aMap, ridePath,
                            mRideRouteResult.getStartPos(),
                            mRideRouteResult.getTargetPos());
//                    rideRouteOverlay.removeFromMap();
                    rideRouteOverlay.addToMap();
//                    rideRouteOverlay.zoomToSpan();
                } else if (result != null && result.getPaths() == null) {
                    ToastUtil.show(mContext, R.string.no_result);
                }
            } else {
                ToastUtil.show(mContext, R.string.no_result);
            }
        } else {
            ToastUtil.showerror(mContext, errorCode);
        }
    }

    @Override
    public void onMapLoaded() {

    }
}

